/**
 * 79. 单词搜索
 * https://leetcode-cn.com/problems/word-search/
 */
public class Solutions_79 {
    public static void main(String[] args) {
        char[][] board = {{'A', 'B', 'C', 'E'},
                          {'S', 'F', 'C', 'S'},
                          {'A', 'D', 'E', 'E'}};

//        String word = "ABCCED";  // output: true
//        String word = "SEE";  // output: true
        String word = "ABCB";  // output: false

//        char[][] board = {{'A', 'B', 'C', 'E'},
//                          {'S', 'F', 'E', 'S'},
//                          {'A', 'D', 'E', 'E'}};

//        String word = "ABCESEEEFS";  // output: true

        boolean result = exist(board, word);
        System.out.println(result);
    }

    // 递归时，走上、下、左、右四个方向
    public static int[][] direction = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    public static int row = 0, col = 0;
    public static boolean exist(char[][] board, String word) {
        char[] arr = word.toCharArray();
        row = board.length;
        col = board[0].length;
        boolean[][] visit = new boolean[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (board[i][j] == arr[0]) {
                    if (dfs(board, arr, 0, visit, i, j)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static boolean dfs(char[][] board, char[] arr, int index,
                              boolean[][] visit, int i, int j) {
        // 结束条件
        if (index == arr.length - 1) {
            // 最后一个字符时
            return board[i][j] == arr[index];
        }
        // 字符不同
        if (arr[index] != board[i][j]) {
            return false;
        }
        visit[i][j] = true;
        for (int[] dir : direction) {
            int x = i + dir[0];
            int y = j + dir[1];
            // 索引越界或者已经访问过
            if (x < 0 || x >= row || y < 0 || y >= col || visit[x][y]) {
                continue;
            }
            boolean res = dfs(board, arr, index + 1, visit, x, y);
            if (res) {
                // 说明能够走完路径
                return true;
            }
        }
        // [i, j] 本次走不通，还原为 false 状态
        visit[i][j] = false;
        return false;
    }
}
